import React from 'react';
import {connect, routerRedux} from 'dva';
import {Button, Layout} from 'antd';
import BaseComponent from 'components/BaseComponent';
import createColumns from "@/routes/Lessons/routers/Detail/components/columns";
import Toolbar from "components/Toolbar";
import {DeleteOutlined, PlusOutlined} from "@ant-design/icons";
import DataTable from "components/DataTable";
import {ModalForm} from "components/Modal";
import * as QueryString from 'query-string'
const { Content, Header, Footer } = Layout;
const Pagination = DataTable.Pagination;


@connect(({ lessonDetail, loading }) => ({
  lessonDetail,
  loading:  loading.models.lessonDetail,
}))

export default class extends BaseComponent {
  state= {
    lessonId: null,
    record: null,
    visible: false,
    rows: [],
  };

  componentDidMount() {
    const {location,dispatch} = this.props;
    const params =  QueryString.parse(location.search);
    if(params.id && params.id != ''){
      dispatch({
        type:'lessonDetail/loadLectureData',
        payload: params,
      });
      this.setState({lessonId: params.id});
    }else{
      dispatch(routerRedux.replace('/lessons'));
    }
  }

  handleDelete = records => {
    const { rows, lessonId } = this.state;

    this.props.dispatch({
      type: 'lessonDetail/remove',
      payload: {
        records,
        lessonId,
        success: () => {
          // 如果操作成功，在已选择的行中，排除删除的行
          this.setState({
            rows: rows.filter(
                item => !records.some(jtem => jtem.id === item.id)
            )
          });
        }
      }
    });
  };

  onUpdate = record =>{
    this.props.dispatch({
      type: 'lessonDetail/getDocumentList',
      payload: {lectureId: record.id}
    });
    this.setState({
      record,
      visible: true
    });
  };

  documentUpload = record =>{
    this.props.dispatch({
      type: 'lessonDetail/getDocumentList',
      payload: {lectureId: record.id}
    });
    this.setState({
      record,
      filesFormVisible: true,
    })
  };

  handleDocumentDelete= uid =>{
    this.props.dispatch({
      type: 'lessonDetail/deleteDocument',
      payload: {
        id: uid,
      }
    })
  };

  handleLectureAddOrUpdate= (values)=>{
    let type = 'lessonDetail/save';
    if (values.id){
      type = 'lessonDetail/update';
    }
    const { lessonId } = this.state;

    const video = values.video[0];
    if(video.hasOwnProperty('originFileObj')) {
      this.setFileInfo(video.originFileObj, values, lessonId, (values, lessonId)=>{
        this.props.dispatch({
          type,
          payload: {
            values,
            lessonId,
            success: () => {
              this.setState({
                record: null,
                visible: false
              });
            }
          }
        })
      });
    }else{
      this.props.dispatch({
        type,
        payload: {
          values,
          lessonId,
          success: () => {
            this.setState({
              record: null,
              visible: false
            });
          }
        }
      })
    }
  };

  setFileInfo = (file, values, lessonId, callback) => {
    const tempURL = window.URL || window.webkitURL;
    let video = document.createElement('video');
    video.preload = 'metadata';
    video.onloadedmetadata = (e) => {
      window.URL.revokeObjectURL(video.src);
      var duration = video.duration;
      file.duration = parseInt(duration);
    };
    video.src = tempURL.createObjectURL(file);

    this.waitDuration(file, values, lessonId, callback);
  };

  waitDuration = (file, values, lessonId, callback) => {
    if(!file.duration){
      setTimeout(this.waitDuration, 1000, file, values, lessonId, callback);
    }else{
      callback(values, lessonId);
    }
  };

  render() {
    const { lessonDetail, loading, dispatch} = this.props;
    const { pageData, lecturers, documentList, videoInfo, examList, examId } = lessonDetail;
    const columns = createColumns(this, lecturers, examList);
    const { rows, record, visible, lessonId} = this.state;

    if (record) {
      record.files = documentList;
      record.video = videoInfo;
      record.exams = examId;
    }

    const dataTableProps = {
      loading,
      columns,
      rowKey: 'id',
      dataItems: pageData,
      selectType: 'checkbox',
      showNum: true,
      isScroll: true,
      selectedRowKeys: rows.map(item => item.id),
      onChange: ({ pageNum, pageSize }) => {
        dispatch({
          type: 'lessons/getPageInfo',
          payload: {
            pageData: pageData.jumpPage(pageNum, pageSize)
          }
        });
      },
      onSelect: (keys, rows) => this.setState({ rows })
    };

    const modalFormProps = {
      loading,
      record,
      visible,
      columns,
      modalOpts: {
        width: 700
      },
      onCancel: () => {
        this.setState({
          record: null,
          visible: false
        });
      },
      onSubmit: values => {
        this.handleLectureAddOrUpdate(values);

      }
    };

    return (
      <Layout className="full-layout page">
        <Header>
          <Toolbar
              appendLeft={
                <Button.Group>
                  <Button type="primary" icon={<PlusOutlined />} onClick={this.onAdd}>
                    新增
                  </Button>
                  <Button
                      disabled={!rows.length}
                      onClick={e => this.onDelete(rows)}
                      icon={<DeleteOutlined />}
                  >
                    删除
                  </Button>
                </Button.Group>
              }
              // pullDown={<SearchBar type="grid" {...searchBarProps} />}
          >
            {/*<SearchBar group="abc" {...searchBarProps} />*/}
          </Toolbar>
        </Header>
        <Content>
          <DataTable {...dataTableProps} />
        </Content>
        {/*<Footer>*/}
        {/*  <Pagination {...dataTableProps} />*/}
        {/*</Footer>*/}
        <ModalForm {...modalFormProps} />
        {/*<ModalForm {...filesFormProps} />*/}
      </Layout>
    );
  }
}
